package com.ldk.base.framework.util;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * 
 * @author mqy
 *
 */
public class HttpUtil {
	
	/**
	 * 
	 * @param uri
	 * @param queryParam
	 * @return
	 */
	public static String get(String uri, String queryParam, Map<String, String> headers){
		if (queryParam != null) {
	      if (uri.indexOf('?') == -1) {
	          uri += '?';
	      }
	      uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
	    }
		HttpGet httpGet = new HttpGet(uri);
		CloseableHttpClient httpClient = HttpClients.custom().build();
		
		if(headers != null && !headers.isEmpty()){
			for(Map.Entry<String, String> entity:headers.entrySet()){
				httpGet.setHeader(entity.getKey(), entity.getValue());
			}
		}
		
		try{
			CloseableHttpResponse response = httpClient.execute(httpGet);
			final StatusLine statusLine = response.getStatusLine();
		    final HttpEntity entity = response.getEntity();
		    if (statusLine.getStatusCode() >= 300) {
		      EntityUtils.consume(entity);
		    }
		    return entity == null ? "" : EntityUtils.toString(entity, Consts.UTF_8);
		}
		catch(Exception e){
			
		}
	    return "";
	}
	
	/**
	 * 
	 * @param uri
	 * @param postParam
	 * @return
	 */
	public static String post(String uri, String postParam, Map<String, String> headers){
		
		HttpPost httpPost = new HttpPost(uri);
		
		CloseableHttpClient httpClient = HttpClients.custom().build();
		
		if(postParam != null && !StringUtils.isEmpty(postParam)){
			HttpEntity entity = new StringEntity(postParam, Consts.UTF_8);
			httpPost.setEntity(entity);
		}
		if(headers != null && !headers.isEmpty()){
			for(Map.Entry<String, String> entity:headers.entrySet()){
				httpPost.setHeader(entity.getKey(), entity.getValue());
			}
		}
		try{
			CloseableHttpResponse response =  httpClient.execute(httpPost);
			final StatusLine statusLine = response.getStatusLine();
		    final HttpEntity entity = response.getEntity();
		    if (statusLine.getStatusCode() >= 300) {
		      EntityUtils.consume(entity);
		    }
		    return entity == null ? "" : EntityUtils.toString(entity, Consts.UTF_8);
		}
		catch(Exception e){
			
		}
		
		return "";
	}
}
